package com.ruoyi.system.service.impl;

import java.util.List;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.TbProduct;
import com.ruoyi.system.mapper.TbProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.TbOrderMapper;
import com.ruoyi.system.domain.TbOrder;
import com.ruoyi.system.service.ITbOrderService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-04-23
 */
@Service
public class TbOrderServiceImpl implements ITbOrderService 
{
    @Autowired
    private TbOrderMapper tbOrderMapper;

    @Autowired
    private TbProductMapper tbProductMapper;

    /**
     * 查询订单
     * 
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public TbOrder selectTbOrderById(Long id)
    {
        return tbOrderMapper.selectTbOrderById(id);
    }

    /**
     * 查询订单列表
     * 
     * @param tbOrder 订单
     * @return 订单
     */
    @Override
    public List<TbOrder> selectTbOrderList(TbOrder tbOrder)
    {
        return tbOrderMapper.selectTbOrderList(tbOrder);
    }

    /**
     * 新增订单
     * 
     * @param tbOrder 订单
     * @return 结果
     */
    @Override
    @Transactional
    public int insertTbOrder(TbOrder tbOrder) throws Exception
    {
        // 扣减产品库存，增加销量
        TbProduct tbProduct = tbProductMapper.selectTbProductById(tbOrder.getProductId());
        long l = tbProduct.getInventory() - tbOrder.getNum();
        if (l < 0) {
            throw new Exception("库存不足！");
        }
        tbProduct.setInventory(l);
        tbProduct.setSales(tbProduct.getSales() + 1);
        tbProductMapper.updateTbProduct(tbProduct);

        return tbOrderMapper.insertTbOrder(tbOrder);
    }

    /**
     * 修改订单
     * 
     * @param tbOrder 订单
     * @return 结果
     */
    @Override
    public int updateTbOrder(TbOrder tbOrder)
    {
        return tbOrderMapper.updateTbOrder(tbOrder);
    }

    /**
     * 批量删除订单
     * 
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteTbOrderByIds(Long[] ids)
    {
        return tbOrderMapper.deleteTbOrderByIds(ids);
    }

    /**
     * 删除订单信息
     * 
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteTbOrderById(Long id)
    {
        return tbOrderMapper.deleteTbOrderById(id);
    }
}
